package com.cd.university.config.security.validate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.Map;

/**
 * 查找具体的验证码处理器
 * @author 陈栋
 * @create 2021/9/4 19:10
 */
@Component
public class ValidateCodeProcessorHolder {
    /**
     * 找到容器中实现了ValidateCodeProcessor效验码处理器的注册了的bean类
     * 就是注入SmsProcessorHolder与ImageProcessorHolder还有EmailProcessorHolder
     */
    @Autowired
    private Map<String ,ValidateCodeProcessor> validateCodeProcessors;

    public ValidateCodeProcessor findValidateCodeProcessor(ValidateCodeType validateCodeType) {
        return findValidateCodeProcessor(validateCodeType.toString());
    }

    public ValidateCodeProcessor findValidateCodeProcessor(String  type) {
        // 这里有个特列，当申请生成电话验证码时，前端接收的参数为mobile，但是后端bean的名字叫做sms，
        // 所以这里进行转换
        if ("mobile".equals(type)) {
            type = "sms";
        }
        String codeProcessorName = type.toLowerCase() + ValidateCodeProcessor.class.getSimpleName();
        ValidateCodeProcessor validateCodeProcessor = validateCodeProcessors.get(codeProcessorName);

        if (validateCodeProcessor==null) {
            throw new ValidateCodeException("验证码处理器" + codeProcessorName + "不存在");
        }

        return validateCodeProcessor;
    }
}
